﻿using System;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace Simple.Common.Json
{
    public class NullableEnumJsonConverter<T> : JsonConverter<T?> where T : struct, Enum
    {
        public override T? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            if (reader.TokenType == JsonTokenType.Null)
            {
                return null;
            }

            return JsonSerializer.Deserialize<T>(ref reader, options);
        }

        public override void Write(Utf8JsonWriter writer, T? value, JsonSerializerOptions options)
        {
            if (value.HasValue)
            {
                JsonSerializer.Serialize(writer, value.Value, options);
            }
            else
            {
                writer.WriteNullValue();
            }
        }
    }

    public class DateTimeNullableJsonConverter : JsonConverter<DateTime?>
    {
        private readonly string format;

        public DateTimeNullableJsonConverter(string format = "yyyy-MM-ddTHH:mm:ss")
        {
            this.format = format;
        }

        public override DateTime? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            if (reader.TokenType == JsonTokenType.Null)
                return null;

            if (reader.TokenType != JsonTokenType.String)
                throw new JsonException($"Unexpected token type: {reader.TokenType}");

            if (!DateTime.TryParseExact(reader.GetString(), format, null, System.Globalization.DateTimeStyles.None, out var dateTime))
                throw new JsonException($"Unable to parse DateTime value: {reader.GetString()}");

            return dateTime;
        }

        public override void Write(Utf8JsonWriter writer, DateTime? value, JsonSerializerOptions options)
        {
            if (value.HasValue)
                writer.WriteStringValue(value.Value.ToString(format));
            else
                writer.WriteNullValue();
        }
    }
}
